import { pages, subPackages, tabBar } from '@/pages.json'
const baseurl = ref(import.meta.env.VITE_SERVER_BASEURL)

/** 判断当前页面是否是tabbar页  */
export const getIsTabbar = () => {
  if (!tabBar) {
    return false
  }
  if (!tabBar.list.length) {
    // 通常有tabBar的话，list不能有空，且至少有2个元素，这里其实不用处理
    return false
  }
  // getCurrentPages() 至少有1个元素，所以不再额外判断
  const lastPage = getCurrentPages().at(-1)
  const currPath = lastPage.route
  return !!tabBar.list.find((e) => e.pagePath === currPath)
}

/**
 * 获取当前页面路由的 path 路劲和 redirectPath 路径
 * path 如 ‘/pages/login/index’
 * redirectPath 如 ‘/pages/demo/base/route-interceptor’
 */
export const currRoute = () => {
  // getCurrentPages() 至少有1个元素，所以不再额外判断
  const lastPage = getCurrentPages().at(-1)
  const currRoute = (lastPage as any).$page
  // console.log('lastPage.$page:', currRoute)
  // console.log('lastPage.$page.fullpath:', currRoute.fullPath)
  // console.log('lastPage.$page.options:', currRoute.options)
  // console.log('lastPage.options:', (lastPage as any).options)
  // 经过多端测试，只有 fullPath 靠谱，其他都不靠谱
  const { fullPath } = currRoute as { fullPath: string }
  // console.log(fullPath)
  // eg: /pages/login/index?redirect=%2Fpages%2Fdemo%2Fbase%2Froute-interceptor (小程序)
  // eg: /pages/login/index?redirect=%2Fpages%2Froute-interceptor%2Findex%3Fname%3Dfeige%26age%3D30(h5)
  return getUrlObj(fullPath)
}

const ensureDecodeURIComponent = (url: string) => {
  if (url.startsWith('%')) {
    return ensureDecodeURIComponent(decodeURIComponent(url))
  }
  return url
}
/**
 * 解析 url 得到 path 和 query
 * 比如输入url: /pages/login/index?redirect=%2Fpages%2Fdemo%2Fbase%2Froute-interceptor
 * 输出: {path: /pages/login/index, query: {redirect: /pages/demo/base/route-interceptor}}
 */
export const getUrlObj = (url: string) => {
  const [path, queryStr] = url.split('?')
  // console.log(path, queryStr)

  if (!queryStr) {
    return {
      path,
      query: {},
    }
  }
  const query: Record<string, string> = {}
  queryStr.split('&').forEach((item) => {
    const [key, value] = item.split('=')
    // console.log(key, value)
    query[key] = ensureDecodeURIComponent(value) // 这里需要统一 decodeURIComponent 一下，可以兼容h5和微信y
  })
  return { path, query }
}
/**
 * 得到所有的需要登录的pages，包括主包和分包的
 * 这里设计得通用一点，可以传递key作为判断依据，默认是 needLogin, 与 route-block 配对使用
 * 如果没有传 key，则表示所有的pages，如果传递了 key, 则表示通过 key 过滤
 */
export const getAllPages = (key = 'needLogin') => {
  // 这里处理主包
  const mainPages = [
    ...pages
      .filter((page) => !key || page[key])
      .map((page) => ({
        ...page,
        path: `/${page.path}`,
      })),
  ]
  // 这里处理分包
  const subPages: any[] = []
  subPackages.forEach((subPageObj) => {
    // console.log(subPageObj)
    const { root } = subPageObj

    subPageObj.pages
      .filter((page) => !key || page[key])
      .forEach((page: { path: string } & Record<string, any>) => {
        subPages.push({
          ...page,
          path: `/${root}/${page.path}`,
        })
      })
  })
  const result = [...mainPages, ...subPages]
  // console.log(`getAllPages by ${key} result: `, result)
  return result
}

/**
 * 得到所有的需要登录的pages，包括主包和分包的
 * 只得到 path 数组
 */
export const getNeedLoginPages = (): string[] => getAllPages('needLogin').map((page) => page.path)

/**
 * 得到所有的需要登录的pages，包括主包和分包的
 * 只得到 path 数组
 */
export const needLoginPages: string[] = getAllPages('needLogin').map((page) => page.path)

export function formatTime(time: Date | number | string, fmt: string) {
  if (!time) return ''
  else {
    const date = new Date(time)
    const o = {
      'M+': date.getMonth() + 1,
      'd+': date.getDate(),
      'H+': date.getHours(),
      'm+': date.getMinutes(),
      's+': date.getSeconds(),
      'q+': Math.floor((date.getMonth() + 3) / 3),
      S: date.getMilliseconds(),
    }
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
    }
    for (const k in o) {
      if (new RegExp('(' + k + ')').test(fmt)) {
        fmt = fmt.replace(
          RegExp.$1,
          RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length),
        )
      }
    }
    return fmt
  }
}
export function formatRichText(html) {
  if (!html) return
  let newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
    match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '')
    match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '')
    match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '')
    return match
  })
  newContent = newContent.replace(/style="[^"]+"/gi, function (match, capture) {
    match = match
      .replace(/width:[^;]+;/gi, 'max-width:100%;')
      .replace(/width:[^;]+;/gi, 'max-width:100%;')
    return match
  })
  newContent = newContent.replace(/<br[^>]*\/>/gi, '')
  newContent = newContent.replace(
    /\<img/gi,
    '<img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;"',
  )

  return newContent
}
export function dealTxt(htmlStr) {
  console.log('htmlStr', htmlStr) // 从接口获取到富文本内容
  const apiSource = baseurl.value // 地址端口
  const _imgL = '<img src="'
  const _video = '<video src="'
  const _href = '<a href="'

  if (htmlStr) {
    // 解析富文本，获取所有图片标签或链接
    const regex = /<img.*?src=["'](.*?)["']/g
    const images = []
    let match
    while ((match = regex.exec(htmlStr)) !== null) {
      images.push(match[1])
    }
    // 遍历每个图片链接，判断是否有前缀
    for (const image of images) {
      if (image.startsWith('http://') || image.startsWith('https://')) {
        console.log(`${image} 包含前缀`)
      } else {
        console.log(`${image} 不包含前缀`)
        // 给没有前缀的图片URL添加apiSource前缀
        if (htmlStr.includes(_imgL)) {
          htmlStr = htmlStr.replace(
            /<img src=\"/g,
            '<img style="width:100%;height:auto" class="ui-iva" src="' + apiSource,
          )
          console.log(htmlStr.includes(_imgL), '=====')
        }
      }
    }
    if (htmlStr.includes(_video)) {
      htmlStr = htmlStr.replace(/<source src=\"/g, '<source src="ui-iva' + apiSource)
    }
    if (htmlStr.includes(_href)) {
      htmlStr = htmlStr.replace(/<a href=\"/g, '<a href="' + apiSource)
    }
  }
  console.log('htmlStr', htmlStr)
  return htmlStr
}

export const handleTree = (data: any[], id?: string, parentId?: string, children?: string) => {
  if (!Array.isArray(data)) {
    console.warn('data must be an array')
    return []
  }
  const config = {
    id: id || 'id',
    parentId: parentId || 'parentId',
    childrenList: children || 'children',
  }

  const childrenListMap = {}
  const nodeIds = {}
  const tree: any[] = []

  for (const d of data) {
    const parentId = d[config.parentId]
    if (childrenListMap[parentId] == null) {
      childrenListMap[parentId] = []
    }
    nodeIds[d[config.id]] = d
    childrenListMap[parentId].push(d)
  }

  for (const d of data) {
    const parentId = d[config.parentId]
    if (nodeIds[parentId] == null) {
      tree.push(d)
    }
  }

  for (const t of tree) {
    adaptToChildrenList(t)
  }

  function adaptToChildrenList(o) {
    if (childrenListMap[o[config.id]] !== null) {
      o[config.childrenList] = childrenListMap[o[config.id]]
    }
    if (o[config.childrenList]) {
      for (const c of o[config.childrenList]) {
        adaptToChildrenList(c)
      }
    }
  }

  return tree
}
// 处理后台返回的富文本照片
export const updateImageUrls = (richText) => {
  const imgRegex = /<img\s+([^>]*)>/gi
  let updatedRichText = richText
  let match

  while ((match = imgRegex.exec(updatedRichText)) !== null) {
    const originalImgTag = match[0]
    const attributes = match[1].split(/\s+/).filter((attr) => attr.trim() !== '') // 分割并过滤空属性

    const attrsMap = {}
    attributes.forEach((attr) => {
      const [key, value] = attr.split('=')
      if (key && value) {
        attrsMap[key.trim()] = value.trim().replace(/^['"]|['"]$/g, '') // 去除属性值两端的引号
      }
    })
    const src = attrsMap.src || ''
    let newUrl
    if (!src.startsWith('http://') && !src.startsWith('https://')) {
      newUrl = `${baseurl.value}${src}`
    } else {
      newUrl = src
    }
    let newImgTag = `<img src="${newUrl}"`
    Object.keys(attrsMap).forEach((key) => {
      if (key !== 'src') {
        newImgTag += ` ${key}="${attrsMap[key]}"`
      }
    })
    newImgTag += ' style="max-width:100%;height:auto;display:block;margin:0 auto;"'
    newImgTag += '>'
    updatedRichText = updatedRichText.replace(originalImgTag, newImgTag)
  }
  return updatedRichText
}
